<template>
  <div class="page">
    <header>
      <div class="common">
        <i ico="s94" class="ico-fx" style="transform: rotate(270deg);" @click="$router.back()"></i>
        <h2 class="max">小说下载</h2>
      </div>
    </header>
    <div>
      <van-form @submit="onsubmit" @failed="onfailed" required="auto">

        <van-cell-group inset title="基础配置">
          <van-field name="url" v-model="config.url" label="目录页地址" :rules="[{ required: true, message: '请填写目录页地址' }]" />
          <van-field name="title" v-model="config.title" label="标题" :rules="[{ required: true, message: '请填写标题' }]" />
          <van-field name="save_dir" v-model="config.save_dir" label="保存目录" />
          <van-field name="save_name" v-model="config.save_name" label="文件名" :rules="[{ required: true, message: '请填写文件名模板' }]" />
          <van-field name="timeout" v-model="config.timeout" label="延迟(ms)" />
        </van-cell-group>

        <van-cell-group inset title="章节列表">
          <van-field name="chapter_key" v-model="config.chapter_key" label="元素标识" :rules="[{ required: true, message: '请填写章节元素标识' }]" />
          <van-field name="chapter_start" v-model="config.chapter_start" type="digit" label="章节截断" placeholder="从第几个章节元素开始下载" />

          <van-field label="链接类型">
            <template #input>
              <radio name="chapter_url_type" v-model="config.chapter_url_type" config="href属性|href"></radio>
            </template>
          </van-field>

          <van-field label="标题类型">
            <template #input>
              <radio name="chapter_type" v-model="config.chapter_type" config="默认|default,添加序列(第1章 标题)|index,不插入章节标题|none"></radio>
            </template>
          </van-field>

        </van-cell-group>

        <van-cell-group inset title="章节内容">
          <van-field name="content_key" v-model="config.content_key" label="元素标识" :rules="[{ required: true, message: '请填写内容元素标识' }]" />
          <van-field label="子元素类型" placeholder="选择保留的子元素类型">
            <template #input>
              <checkbox name="content_type" v-model="config.content_type" config="BR,P,DIV"></checkbox>
            </template>
          </van-field>
        </van-cell-group>

        <van-cell-group inset title="清除字符串">
          <van-swipe-cell v-for="(v,i) in config.clear_arr">
            <input type="hidden" name="clear_arr[]" :value="v">
            <van-cell center :title="v" />
            <template #right>
              <van-button square type="danger" text="删除" @click="config.clear_arr.splice(i,1)" />
            </template>
          </van-swipe-cell>

          <van-field v-model="cache_clear">
            <template #button>
              <van-button size="small" type="primary" @click="add_clear">添加</van-button>
            </template>
          </van-field>
        </van-cell-group>

        <input ref="submit" type="submit" style="display: none;">

      </van-form>
    </div>

    <footer>
      <div class="download_book-btns flex">
        <van-button @click="auto_config">智能分析</van-button>

        <van-button v-if="runing" @click="cancel" type="danger">{{stop ? '取消中...' : '取消'}}</van-button>
        <van-button v-else @click="$refs.submit.click()" type="primary">开始下载</van-button>
      </div>
    </footer>
  </div>

  <van-popup v-model:show="show_auto_config" safe-area-inset-top safe-area-inset-bottom>
    <div class="auto_config">
      <h2>{{auto_res.title}}</h2>
      <ul>
        <li v-for="(row,i) in auto_res.show_chapters"><span style="display: inline-block;width: 2em;">{{i}}</span>{{row.title}}</li>
        <li v-if="auto_res.chapters.length" style="text-align: center;">...此次省略 {{auto_res.chapters.length}} 个章节...</li>
      </ul>
      <h3 style="margin-top: 0.1rem;">{{auto_res.chapters_row.title}}</h3>
      <div>{{auto_res.chapters_row.content_html}}</div>
    </div>
  </van-popup>
</template>

<script>
import s94 from 's94-js';
import download_book from './download_book.js'
import {loading, msg} from "@/js/vant_tool.js";

export default {
  name: "download_book",
  data(){
    return {
      cache_clear: '',
      show_auto_config: false,
      config: {
        url: 'http://www.2kk.la/ks69310/',
        title: '下载小说',
        chapter_key: '#list dd>a',
        chapter_start: 0,
        chapter_url_type: 'href',
        chapter_type: 'default',
        content_key: '#content',
        content_type: 'BR,P',
        clear_arr: ['内容更新后，请重新刷新页面，即可获取最新更新！'],
        save_dir: '',
        save_name: '{{title}}_{{host}}_{{id}}',
        timeout: '100',
      },
      pgs: {ok:0, count:0},
      stop: false,
      runing: false,
      auto_res: {
        title: '标题',
        show_chapters: [{title:'111111'},{title:'2222222'}],
        chapters: [],
        chapters_row: {
          title: '标题',
          content: '标题标题标题标题标题标题标题标题标题标题标题标题标题标题',
          content_html: "标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题",
        },
      }
    }
  },
  methods: {
    add_clear(){
      if (!this.cache_clear) return;
      this.config.clear_arr.push(this.cache_clear);
      this.cache_clear = '';
    },
    cancel(){
      if (this.stop) msg('取消中...');
      this.stop = true;
    },
    onfailed(e){
      let err_msg = [];
      if (Array.isArray(e.errors)){
        e.errors.forEach((v)=>{err_msg.push(v.message)});
      }else {
        err_msg.push(e.errors.message);
      }
      msg(err_msg.join('；'))
    },
    onsubmit(){
      let app = this;
      app.stop = false;
      app.runing = true;
      download_book({
        url: app.config.url,
        get_chapter(dom) {
          let res = [];
          let list = dom.querySelectorAll(app.config.chapter_key);
          if (!list.length) throw '章节元素不存在，请核对章节元素标识';
          list.forEach(function (v) {
            let href = '';
            switch (app.config.chapter_url_type) {
              case 'href': {
                href = v.getAttribute('href');
              }break;
            }
            if (!/^\//.test(href)) return;
            res.push({
              title: v.innerHTML,
              url: href,
            })
          })
          if (!res.length) throw '章节数量为0，请核对章节的链接类型';
          return res;
        },
        get_content(dom) {
          let content_dom = dom.querySelector(app.config.content_key);
          let del_doms = dom.querySelectorAll(app.config.content_key + '>*');
          let need_node = app.config.content_type.split(',');
          del_doms.forEach(function (v) {
            if (!~need_node.indexOf(v.nodeName)) {
              content_dom.removeChild(v);
            }
          });
          let content = content_dom.innerHTML;
          return content;
        },
        title: app.config.title,
        clear_arr: app.config.clear_arr,
        chapter_start: app.config.chapter_start,
        chapter_type: app.config.chapter_type,
        save_name: app.config.save_name,
        save_dir: app.config.save_dir,
        timeout: parseInt(app.config.timeout),
        progress(pgs, row){
          msg('下载进度：'+pgs.ok+'/'+pgs.count);
          return !app.stop;
        },
        success(res){
          msg('下载完成，正在合成内容...');
          app.runing = false;
        },
        error(errmsg){
          app.runing = false;
          msg('下载出错：'+errmsg);
        },
      })
    },
    auto_config(){
      let app = this;
      if (!this.config.url) return msg('目录页地址必填');
      loading.show();
      download_book.auto_config(this.config.url).then(function (res){
        s94.each(res.config, function (v,k){ app.config[k] = v; });
        res.show_chapters = res.chapters.splice(0, 30);
        app.auto_res = res;
        setTimeout(function (){
          app.show_auto_config = true;
        }, 500);
        msg('解析成功');
      }).catch(function (errmsg){
        msg('分析出错：'+errmsg);
      });
    },
  },
  mounted(){
    let app = this;
    window['app'] = app;
    s94(function (){
      return
      msg('仅APP可用');
      app.$router.back();
    }, ~s94.OS_APP);
  },
  beforeUnmount(){
    this.stop = true;
  },
}
</script>

<style scoped>
.auto_config{padding: 10px;}
.download_book-btns{justify-content: space-between;padding: 5px 10px;font-size: 20px;}
</style>